/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 8.3下午2.c
> Author:
> Mail: 
> Created Time: Sun 04 Aug 2024 03:51:20 AM PDT
***************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <time.h>
#include <sys/types.h>
//用父子进程分别操作同一个文件，父和子都给其中写10次当前时间
int main(int argc,const char* argv[])
{
	time_t tm = time(NULL);
	struct tm *p=localtime(&tm);
	pid_t pid = 0;
	int i=0;
	char buf[20]={0};
	pid = fork();
	if(pid == 0)
	{ 
		int fd = 0;
		fd =open("./music/test.txt",O_RDWR|O_APPEND);
		if(fd == -1)
		{
			perror("open");
		}
		while(i<10)
		{
			printf("子进程打印时间:%s\n",asctime(p));
			int res  =write(fd,buf,sizeof(buf));
			memset(buf,0,sizeof(buf));
			if(res == -1)
			{
				perror("write");
			}
			sleep(1);
			i++;
		}
		close(fd);
		exit(-1);
	}else if(pid < 0)
	{
		printf("fork error\n");
	}

	int fd = open("./music/temp.txt",O_RDWR|O_APPEND);
	if(fd == -1)
	{
		perror("open");
	}
	while(i < 10)
	{
		char buf[20]={0};
		time_t tm =time(NULL);
		struct tm *p = localtime(&tm);
		printf("父进程打印时间:%s\n",asctime(p));
		int res =write(fd,buf,sizeof(buf));
		memset(buf,0,sizeof(buf));
		if(res == -1)
		{
			perror("write");
		}
		sleep(1);
		i++;
	}
	close(fd);
	wait(NULL);
	return 0;
}
